package com.example.rotateimageview.animationVies;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.rotateimageview.MyApplication;

public class MyView extends View {
    private Bitmap bitmap;
    private Paint paint;
    private PaintFlagsDrawFilter paintFlagsDrawFilter;
    private int mW,mH;

    public MyView(Context context) {
        super(context);
        init();
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mW =getMeasuredWidth();
        mH = getMeasuredHeight();
    }

    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paintFlagsDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
                | Paint.FILTER_BITMAP_FLAG);
    }


    @Override
    protected void onDraw(Canvas canvas) {

    }


    @Override
    protected void dispatchDraw(Canvas canvas) {
        paint.reset();
        // 消除锯齿
        paint.setAntiAlias(true);
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        canvas.setDrawFilter(paintFlagsDrawFilter);
        canvas.drawBitmap(bitmap, 0, 0, paint);
    }

    public void setBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        this.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED);
        float scaleWidth = ((float) dip2px(160)) / width;
        float scaleHeight = ((float) dip2px(160)) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbm = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        this.bitmap = newbm;
        postInvalidate();
    }

    public static int dip2px(float dpValue) {
        final float scale = MyApplication.instance.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
